package com.example.liulin.catchcrazycat;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;

/**
 * Created by LiuLin on 2017/1/13.
 */

public class Playground extends SurfaceView implements View.OnTouchListener {
    private static  final int ROW=10;
    private static final  int COL=10;
    private static  final int BLOCKS=10;//默认添加的路障数量

    private Dot matrix[][];
    private Dot cat;

    public Playground(Context context) {
        super(context);
        getHolder().addCallback(callback);
        matrix=new Dot[ROW][COL];
        for(int i=0;i<ROW;i++){
            for (int j=0;j<COL;j++){
                matrix[i][j]=new Dot(j,i);
            }
        }
        setOnTouchListener(this);
        initGame();
    }
    private Dot getDot(int x,int y){
        return matrix[y][x];
    }
    //redraw重画
    private void redraw() {
        Canvas canvas = getHolder().lockCanvas();//锁定画布，一般在锁定后就可以通过其返回值画布canvas,在其上面画图等操作了
        canvas.drawColor(Color.CYAN);//设置画布背景颜色
        getHolder().unlockCanvasAndPost(canvas);//结束锁定画图，并提交改变

    }

    SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            redraw();//界面第一次显示时，需要将指定的内容显示到界面上.在创建时激发，一般在这里调用画图的线程
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            //在surface的大小发生改变时激发
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            //销毁时激发，一般在这里将画图的线程停止、释放。
        }
    };
    //游戏初始化
    private void initGame() {
        for (int i = 0; i < ROW; i++) {
            for (int j = 0; j < COL; j++) {
                matrix[i][j].setStatus(Dot.STATUS_OFF);
            }
        }
        cat = new Dot(4, 5);
        getDot(4,5).setStatus(Dot.STATUS_IN);
        for (int i=0;i<BLOCKS;){
            int x=(int)((Math.random()*1000)%COL);
            int y=(int)((Math.random()*1000)%ROW);//random是double类型，所以乘以1000
            if(getDot(x,y).getStatus()==Dot.STATUS_OFF){
                getDot(x,y).setStatus(Dot.STATUS_ON);
                i++;
                Log.v("Block",Integer.toString(i));
                System.out.println(i);
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return false;
    }
}

